const app = getApp()
import { requestApi } from '../../../api'
import { formatPrice } from '../../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 页面配置
    loading: false,
    channel: '',
    total: {},
    couponList: [],
    requestFlag: false,
    couponData: '',
    receiveFlag: true,
    coupon_index: -1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let gid = options.gid || ''
    let channel = options.channel || 'wx_xcx'

    this.data.channel = channel
    this.data.gid = gid

    this.getUseCouponsList(gid)
  },

  /**
   * 页面上拉触底事件的处理函数
   */

  // 获取优惠券列表
  getUseCouponsList: function (gid) {
    let couponList = this.data.couponList
    
    app.request({
      url: requestApi.goodsCouponListUrl,
      method: 'GET',
      login: false,
      data: {
        gid: gid,
      }
    }, (res) => {
      let couponData

      couponData = res.original.data
      if (couponData.receive_available && couponData.receive_available.data.length) {
        couponData.receive_available.data.forEach((couponItem) => {
          couponItem.new_amount = couponItem.amount ? formatPrice(couponItem.amount / 100) : 0
        })
      }

      if (couponData.use_available && couponData.use_available.data.length) {
        couponData.use_available.data.forEach((couponItem) => {
          couponItem.new_amount = couponItem.amount ? formatPrice(couponItem.amount / 100) : 0;
          if(couponItem.use_range){
            couponItem.use_range = JSON.parse(couponItem.use_range);
          }
          
        })
      }

      this.setData({
        loading: true,
        couponData: couponData,
      })
    }, (error) => {
      this.setData({
        loading: true,
      })
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })

    }, () => {
      this.setData({
        requestFlag: false,
      })
    })
  },

  //领取优惠券
  receiveCoupon: function (e) {
    if (!app.toLogin()) {
      this.setData({
        loading: true
      })

      return false
    }

    let coupon_no = e.currentTarget.dataset.coupon

    wx.showLoading({ title: '领取中...' })
    app.request({
      url: requestApi.receiveStoreCouponUrl,
      data: {
        coupon_no: '' + coupon_no
      },
    }, (data) => {
      wx.hideLoading()
      wx.showToast({
        title: data.original.msg,
      })
      this.getUseCouponsList(this.data.gid)
      this.setData({
        receiveFlag: false,
      })
    })
  },

  // 返回上一页
  getAmount: function (e) {
    let amount = e.currentTarget.dataset.amount,
      number = e.currentTarget.dataset.number,
      pages = getCurrentPages(),
      prevPage = pages[pages.length - 2]

    prevPage.setData({
      amount: amount,
      couponId: number
    })

    wx.navigateBack()
  },
})